package com.lbs.jiepiaisi.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.ViewGroup;
import android.view.ViewGroupOverlay;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviStep;
import com.lbs.jiepiaisi.bean.StrategyBean;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class Utils {
    //工单登录是否弹出登录成功Toast
    public static boolean IS_SHOW_SUCCESS = false;
    //工单登录是否弹出设备类型不匹配Toast
    public static boolean IS_SHOW_NOT_SUITABLE = false;
    //工单登录后是否跳转
    public static boolean IS_REDIRECT = false;
    private static DecimalFormat fnum = new DecimalFormat("##0.0");
    public static final int AVOID_CONGESTION = 4;  // 躲避拥堵
    public static final int AVOID_COST = 5;  // 避免收费
    public static final int AVOID_HIGHSPEED = 6; //不走高速
    public static final int PRIORITY_HIGHSPEED = 7; //高速优先

    public static final int START_ACTIVITY_REQUEST_CODE = 1;
    public static final int ACTIVITY_RESULT_CODE = 2;

    public static final String INTENT_NAME_AVOID_CONGESTION = "AVOID_CONGESTION";
    public static final String INTENT_NAME_AVOID_COST = "AVOID_COST";
    public static final String INTENT_NAME_AVOID_HIGHSPEED = "AVOID_HIGHSPEED";
    public static final String INTENT_NAME_PRIORITY_HIGHSPEED = "PRIORITY_HIGHSPEED";


    public static String getFriendlyTime(int s) {
        String timeDes = "";
        int h = s / 3600;
        if (h > 0) {
            timeDes += h + "小时";
        }
        int min = (int) (s % 3600) / 60;
        if (min > 0) {
            timeDes += min + "分钟";
        }else if(min==0){
            timeDes="距离该点附近";
        }
        return timeDes;
    }

    public static String getFriendlyDistance(int m) {
        float dis = m / 1000f;
        String disDes = fnum.format(dis) + "公里";
        return disDes;
    }

    /**
     * 计算path对应的标签
     *
     * @param paths        多路径规划回调的所有路径
     * @param ints         多路径线路ID
     * @param pathIndex    当前路径索引
     * @param strategyBean 封装策略bean
     * @return path对应标签描述
     */
    public static String getStrategyDes(HashMap<Integer, AMapNaviPath> paths, int[] ints, int pathIndex, StrategyBean strategyBean) {
        int StrategyTAGIndex = pathIndex + 1;
        String StrategyTAG = "方案" + StrategyTAGIndex;

        int minTime = Integer.MAX_VALUE;
        int minDistance = Integer.MAX_VALUE;
        int minTrafficLightNumber = Integer.MAX_VALUE;
        int minCost = Integer.MAX_VALUE;
        for (int i = 0; i < ints.length; i++) {
            if (pathIndex == i) {
                continue;
            }
            AMapNaviPath path = paths.get(ints[i]);
            if (path == null) {
                continue;
            }
            int trafficListNumber = getTrafficNumber(path);
            if (trafficListNumber < minTrafficLightNumber) {
                minTrafficLightNumber = trafficListNumber;
            }

            if (path.getTollCost() < minCost) {
                minCost = path.getTollCost();
            }

            if (path.getAllTime() < minTime) {
                minTime = path.getAllTime();
            }
            if (path.getAllLength() < minDistance) {
                minDistance = path.getAllLength();
            }
        }
        AMapNaviPath indexPath = paths.get(ints[pathIndex]);
        int indexTrafficLightNumber = getTrafficNumber(indexPath);
        int indexCost = indexPath.getTollCost();
        int indexTime = indexPath.getAllTime();
        int indexDistance = indexPath.getAllLength();
        if (indexTrafficLightNumber < minTrafficLightNumber) {
            StrategyTAG = "红绿灯少";
        }
        if (indexCost < minCost) {
            StrategyTAG = "收费较少";
        }

        if (Math.round(indexDistance / 100f) < Math.round(minDistance / 100f)) {   // 展示距离精确到千米保留一位小数，比较时按照展示数据处理
            StrategyTAG = "距离最短";
        }
        if (indexTime / 60 < minTime / 60) {    //展示时间精确到分钟，比较时按照展示数据处理
            StrategyTAG = "时间最短";
        }
        boolean isMulti = isMultiStrategy(strategyBean);
        if (strategyBean.isCongestion() && pathIndex == 0 && !isMulti) {
            StrategyTAG = "躲避拥堵";
        }
        if (strategyBean.isAvoidhightspeed() && pathIndex == 0 && !isMulti) {
            StrategyTAG = "不走高速";
        }
        if (strategyBean.isCost() && pathIndex == 0 && !isMulti) {
            StrategyTAG = "避免收费";
        }
        if (pathIndex == 0 && StrategyTAG.startsWith("方案")) {
            StrategyTAG = "推荐";
        }
        return StrategyTAG;
    }


    /**
     * 判断驾车偏好设置是否同时选中多个策略
     *
     * @param strategyBean 驾车策略bean
     * @return
     */
    public static boolean isMultiStrategy(StrategyBean strategyBean) {
        boolean isMultiStrategy = false;
        if (strategyBean.isCongestion()) {
            if (strategyBean.isAvoidhightspeed() || strategyBean.isCost() || strategyBean.isHightspeed()) {
                isMultiStrategy = true;
            } else {
                isMultiStrategy = false;
            }
        }
        if (strategyBean.isCost()) {
            if (strategyBean.isCongestion() || strategyBean.isAvoidhightspeed()) {
                isMultiStrategy = true;
            } else {
                isMultiStrategy = false;
            }
        }
        if (strategyBean.isAvoidhightspeed()) {
            if (strategyBean.isCongestion() || strategyBean.isCost()) {
                isMultiStrategy = true;
            } else {
                isMultiStrategy = false;
            }
        }
        if (strategyBean.isHightspeed()) {
            if (strategyBean.isCongestion()) {
                isMultiStrategy = true;
            } else {
                isMultiStrategy = false;
            }
        }
        return isMultiStrategy;
    }

    public static Spanned getRouteOverView(AMapNaviPath path) {
        String routeOverView = "";
        if (path == null) {
            Html.fromHtml(routeOverView);
        }

        int cost = path.getTollCost();
        if (cost > 0) {
            routeOverView += "过路费约<font color=\"red\" >" + cost + "</font>元";
        }
        int trafficLightNumber = getTrafficNumber(path);
        if (trafficLightNumber > 0) {
            routeOverView += "红绿灯" + trafficLightNumber + "个";
        }
        return Html.fromHtml(routeOverView);
    }

    public static int getTrafficNumber(AMapNaviPath path) {
        int trafficLightNumber = 0;
        if (path == null) {
            return trafficLightNumber;
        }
        List<AMapNaviStep> steps = path.getSteps();
        for (AMapNaviStep step : steps) {
            trafficLightNumber += step.getTrafficLightNumber();
        }
        return trafficLightNumber;
    }

    /**
     * 根据用户的起点和终点经纬度计算两点间距离，此距离为相对较短的距离，单位米。
     *
     * @param startLat
     *           起点的坐标
     * @param endLat
     *           终点的坐标
     * @return
     */
    public static double calculateDistance(double startLat,double startLng, double endLat, double endLng)
    {

        double d1 = 0.01745329251994329D;
        double d2 = startLng;
        double d3 = startLat;
        double d4 = endLng;
        double d5 = endLat;
        d2 *= d1;
        d3 *= d1;
        d4 *= d1;
        d5 *= d1;
        double d6 = Math.sin(d2);
        double d7 = Math.sin(d3);
        double d8 = Math.cos(d2);
        double d9 = Math.cos(d3);
        double d10 = Math.sin(d4);
        double d11 = Math.sin(d5);
        double d12 = Math.cos(d4);
        double d13 = Math.cos(d5);
        double[] arrayOfDouble1 = new double[3];
        double[] arrayOfDouble2 = new double[3];
        arrayOfDouble1[0] = (d9 * d8);
        arrayOfDouble1[1] = (d9 * d6);
        arrayOfDouble1[2] = d7;
        arrayOfDouble2[0] = (d13 * d12);
        arrayOfDouble2[1] = (d13 * d10);
        arrayOfDouble2[2] = d11;
        double d14 = Math.sqrt((arrayOfDouble1[0] - arrayOfDouble2[0]) * (arrayOfDouble1[0] - arrayOfDouble2[0])
                + (arrayOfDouble1[1] - arrayOfDouble2[1]) * (arrayOfDouble1[1] - arrayOfDouble2[1])
                + (arrayOfDouble1[2] - arrayOfDouble2[2]) * (arrayOfDouble1[2] - arrayOfDouble2[2]));

        return (Math.asin(d14 / 2.0D) * 12742001.579854401D);
    }

    //高德地图根据坐标算距离
    public static double calculateLineDistance(double startLat,double startLng, double endLat, double endLng){
         LatLng latLng1 = new LatLng(startLat,startLng);
         LatLng latLng2 = new LatLng(endLat,endLng);
         return  AMapUtils.calculateLineDistance(latLng1,latLng2);
    }

    public static int compareTime(String oldTime, String newTime){
        long now = 0;
        long old = 0;

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//如2016-08-10 20:40
            old = sdf.parse(oldTime).getTime();
            now = sdf.parse(newTime).getTime();
        }catch (Exception e){
            Log.e("hyhyhyhyhyhyERROR",e.getCause()+"");
        }

        int minutes = (int) ((now - old) / (1000 * 60));

        return minutes;
    }

    public static String getNowTime(){
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleFormat.format(new Date());
    }
    public static void main(String[] args){
        System.out.println(compareTime("2018-01-19 17:31:08","2018-01-19 17:51:23"));
    }

    String cityJsonStr = "";

    //读取方法
    public static String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static void setBackgroundAlpha(Context mContext, float bgAlpha) {
//        WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
//        lp.alpha = bgAlpha;
//        ((Activity) mContext).getWindow().setAttributes(lp);

        if (bgAlpha == 1f) {
            clearDim((Activity) mContext);
        }else{
            applyDim((Activity) mContext, bgAlpha);
        }
    }

    private static void applyDim(Activity activity, float bgAlpha) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            ViewGroup parent = (ViewGroup) activity.getWindow().getDecorView().getRootView();
            //activity跟布局
//        ViewGroup parent = (ViewGroup) parent1.getChildAt(0);
            Drawable dim = new ColorDrawable(Color.BLACK);
            dim.setBounds(0, 0, parent.getWidth(), parent.getHeight());
            dim.setAlpha((int) (255 * bgAlpha));
            ViewGroupOverlay overlay = parent.getOverlay();
            overlay.add(dim);
        }
    }

    private static void clearDim(Activity activity) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            ViewGroup parent = (ViewGroup) activity.getWindow().getDecorView().getRootView();
            //activity跟布局
//        ViewGroup parent = (ViewGroup) parent1.getChildAt(0);
            ViewGroupOverlay overlay = parent.getOverlay();
            overlay.clear();
        }
    }

    public static long getFileSize(String f) {
        try {
            File file = new File(f);
            long size = 0;
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();

            } else {
                Log.e("获取文件大小", "文件不存在!");
            }
            return size;
        }catch (Exception e){
            Log.i("util photosize === ", "utils photo size === " + e.getMessage());
        }

        return 0;
    }
}
